package com.xhs.design.adapter.impl;

import com.xhs.design.adapter.ApiAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc:
 * @projectName: tools-parent
 * @author: xhs
 * @date: 2022/12/5 11:04
 * @version: JDK 1.8
 */
@Slf4j
@Service
public class ApiAdapterImpl {

    private List<ApiAdapter> adapterList = new ArrayList<>();

    /**
     * 添加每一种 方式实现的适配器
     */
    public ApiAdapterImpl() {
        adapterList.add(new ApiV1AdapterImpl());
        adapterList.add(new ApiV2AdapterImpl());
    }

    /**
     * 执行Api具体的实现方法
     *
     * @param httpServletRequest
     * @param object
     */
    public Object doService(HttpServletRequest httpServletRequest, Object object) {
        ApiAdapter apiAdapter = getApiAdapter(object);
        return apiAdapter.handle(httpServletRequest, object);
    }

    /**
     * 获取到该Api的具体适配器
     *
     * @param object
     * @return
     */
    public ApiAdapter getApiAdapter(Object object) {
        for (ApiAdapter adapter : adapterList) {
            if (adapter.supports(object)) {
                return adapter;
            }
        }
        return null;
    }
}
